/**
 * 
 */
package id.ac.gunadarma.paracorp.services;

import java.util.List;

import id.ac.gunadarma.paracorp.model.EnglishSentence;
import id.ac.gunadarma.paracorp.model.TranslatedSentence;
import id.ac.gunadarma.paracorp.model.TranslationReference;
import id.ac.gunadarma.paracorp.repository.EnglishSentenceRepository;
import id.ac.gunadarma.paracorp.repository.TranslatedSentenceRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @author rezalesmana
 *
 */
@Service
public class TranslatedSentenceService {
	
	@Autowired
	private EnglishSentenceService englishSentenceService;
	
	@Autowired
	private TranslatedSentenceRepository translatedSentenceRepository;
	
	public TranslatedSentence findById(String id, String language) {
		return getRepository().findById(id, language);
	}
	
	public List<TranslatedSentence> findAll(int pageIndex, int pageSize, String language) {
		return getRepository().findAll(language, constructPageable(pageIndex, pageSize));
	}
	  
	public void save(TranslatedSentence objectToSave) {
		if(objectToSave.getEnglishSentence().getId() == null) {
			EnglishSentence checkDB = this.getEnglishService().findBySentence(
					objectToSave.getEnglishSentence().getSentence());
			if(checkDB != null) {
				objectToSave.setEnglishSentence(checkDB);
			} else {
				objectToSave.setEnglishSentence(this.getEnglishService().save(objectToSave.getEnglishSentence()));
			}
		}
		objectToSave.getEnglishSentence().addTranslationReference(
				TranslationReference.convert(getRepository().save(objectToSave)));
		this.getEnglishService().save(objectToSave.getEnglishSentence());
	}
	
	public void save(List<TranslatedSentence> objectToSaveList) {
		for(TranslatedSentence objectToSave : objectToSaveList) {
			save(objectToSave);
		}
	}
	
	public long getTotalSize(String language) {
		return getRepository().getCount(language);
	}
	
	private Pageable constructPageable(int pageIndex, int pageSize) {
        Pageable pageable = new PageRequest(pageIndex, pageSize);
        return pageable;
    }
	
	private TranslatedSentenceRepository getRepository() {
		return translatedSentenceRepository;
	}
	
	private EnglishSentenceService getEnglishService() {
		return englishSentenceService;
	}

}
